package com.infinitus.activity.util;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.IOUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.Map;

/**
 * @create: 2019/1/9
 * @desc: 封装http协议方法
 */
public class HttpClientUtils {
    private static MultiThreadedHttpConnectionManager manager = null;

    private static HttpClientParams httpClientParams = null;

    private static HttpClient httpClient = null;

    private static String NL = System.getProperty("line.separator");

    static {
        manager = new MultiThreadedHttpConnectionManager();
        manager.getParams().setDefaultMaxConnectionsPerHost(50);
        manager.getParams().setMaxTotalConnections(80);
        manager.getParams().setConnectionTimeout(10000);
        manager.getParams().setSoTimeout(10000);
        httpClientParams = new HttpClientParams();
        httpClientParams.setConnectionManagerTimeout(5000);
        httpClient = new HttpClient(manager);
        httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        httpClient.setParams(httpClientParams);

    }

    private static HttpClient getClient(){
        return httpClient;
    }

    public static String getRequest(String url,int timeOut) throws Exception{
        URL u = new URL(url);
        if("https".equalsIgnoreCase(u.getProtocol())){
            SslUtils.ignoreSsl();
        }
        URLConnection conn = u.openConnection();
        conn.setConnectTimeout(timeOut);
        conn.setReadTimeout(timeOut);
        return IOUtils.toString(conn.getInputStream());
    }

    /**
     * 执行httpGet方法
     *
     * @param url
     * @param params
     *            请求参数 example：key=value
     * @return
     * @throws Exception
     */
    public static String doGet(String url, String... params)
            throws Exception {
        HttpClient client = getClient();
        StringBuilder urlsb = new StringBuilder(url);
        if(params!=null){
            for (String param : params) {
                if (urlsb.indexOf("?") > -1) {
                    urlsb.append("&");
                } else {
                    urlsb.append("?");
                }
                urlsb.append(param);
            }
        }
        GetMethod method = new GetMethod(urlsb.toString());
        try {
            int excuteCode = client.executeMethod(method);
            if (excuteCode == 200) {
                BufferedReader br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(),"UTF-8"));
                StringBuffer resBuffer = new StringBuffer();
                String resTemp = "";
                while ((resTemp = br.readLine())!=null) {
                    resBuffer.append(resTemp).append(NL);;
                }
                return resBuffer.toString();
            }else {
                throw new ServiceException(excuteCode);
            }
        } finally {
            method.releaseConnection();
        }
    }




    /**
     * 执行httpPost方法
     *
     * @param url
     * @param params
     *            请求参数
     * @return
     * @throws HttpException
     * @throws IOException
     * @throws ServiceException
     */
    public static String doPost(String url, Map<String, String> params)
            throws HttpException, IOException, ServiceException {
        HttpClient client = getClient();
        PostMethod method = new PostMethod(url);
        try {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                method.addParameter(entry.getKey(), entry.getValue());
            }
            method.getParams().setContentCharset("UTF-8");
            int excuteCode = client.executeMethod(method);
            if (excuteCode == 200) {
                BufferedReader br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(),"UTF-8"));
                StringBuffer resBuffer = new StringBuffer();
                String resTemp = "";
                while ((resTemp = br.readLine())!=null) {
                    resBuffer.append(resTemp).append(NL);;
                }
                return resBuffer.toString();
            } else {
                throw new ServiceException(excuteCode);
            }
        } finally {
            method.releaseConnection();
        }
    }

    /**
     * 执行httpPost方法
     *
     * @param url
     * @param params
     *            请求参数
     * @return
     * @throws HttpException
     * @throws IOException
     * @throws ServiceException
     */
    public static String doPost(String url, String data) throws HttpException,
            IOException, ServiceException {
        HttpClient httpClient = getClient();
        PostMethod postMethod = new PostMethod(url);
        try {
            postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                    new DefaultHttpMethodRetryHandler());
            ByteArrayRequestEntity be = new ByteArrayRequestEntity(
                    data.getBytes("UTF-8"));
            postMethod.setRequestEntity(be);
            postMethod.getParams().setContentCharset("UTF-8");
            postMethod.addRequestHeader("Content-Type", "text/xml");
            HttpConnectionManagerParams managerParams = httpClient
                    .getHttpConnectionManager().getParams();
            // 设置连接超时时间(单位毫秒)
            managerParams.setConnectionTimeout(120000);
            // 设置读数据超时时间(单位毫秒)
            managerParams.setSoTimeout(120000);
            int statusCode = httpClient.executeMethod(postMethod);
            if (statusCode == org.apache.commons.httpclient.HttpStatus.SC_OK) {
                return postMethod.getResponseBodyAsString();
            }else{
                throw new ServiceException(statusCode);
            }
        } catch (UnknownHostException e) {
            throw new ServiceException(HttpStatus.SC_BAD_GATEWAY);
        } catch (SocketTimeoutException e) {
            throw new ServiceException(HttpStatus.SC_REQUEST_TIMEOUT);
        } finally {
            postMethod.releaseConnection();
        }
    }
    /**
     * 执行httpPost方法
     *
     * @param url
     * @param params
     *            请求参数
     * @return
     * @throws HttpException
     * @throws IOException
     * @throws ServiceException
     */
    public static String doPostByRobot(String url, String data) throws HttpException,
            IOException, ServiceException {
        HttpClient httpClient = getClient();
        PostMethod postMethod = new PostMethod(url);
        try {
            postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                    new DefaultHttpMethodRetryHandler());
            ByteArrayRequestEntity be = new ByteArrayRequestEntity(
                    data.getBytes("UTF-8"));
            postMethod.setRequestEntity(be);
            postMethod.getParams().setContentCharset("UTF-8");
            postMethod.addRequestHeader("Content-Type", "application/json;charset=UTF-8");
            HttpConnectionManagerParams managerParams = httpClient
                    .getHttpConnectionManager().getParams();
            // 设置连接超时时间(单位毫秒)
            managerParams.setConnectionTimeout(120000);
            // 设置读数据超时时间(单位毫秒)
            managerParams.setSoTimeout(120000);
            int statusCode = httpClient.executeMethod(postMethod);
            if (statusCode == org.apache.commons.httpclient.HttpStatus.SC_OK) {
                return postMethod.getResponseBodyAsString();
            }else{
                throw new ServiceException(statusCode);
            }
        } catch (UnknownHostException e) {
            throw new ServiceException(HttpStatus.SC_BAD_GATEWAY);
        } catch (SocketTimeoutException e) {
            throw new ServiceException(HttpStatus.SC_REQUEST_TIMEOUT);
        } finally {
            postMethod.releaseConnection();
        }
    }
    /**
     * Post方法获取字符数组
     * @param url
     * @param params
     * @return
     * @throws HttpException
     * @throws IOException
     * @throws ServiceException
     */
    public static byte[] doPostGetBytes(String url, Map<String, String> params)
            throws HttpException, IOException, ServiceException {
        HttpClient client = getClient();
        PostMethod method = new PostMethod(url);
        try {
            if(params!=null){
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    method.addParameter(entry.getKey(), entry.getValue());
                }
            }
            method.getParams().setContentCharset("UTF-8");
            int excuteCode = client.executeMethod(method);
            if (excuteCode == 200) {
                return method.getResponseBody();
            } else {
                throw new ServiceException(excuteCode);
            }
        } finally {
            method.releaseConnection();
        }
    }


    public static void main(String[] args) throws Exception {
        try {
            String aa=doGet("http://172.20.70.168:7081/ydapi/awardBeauty/login?dealerNo=161907846&password=e10adc3949ba59abbe56e057f20f883e","");
            System.out.println(aa);
        } catch (Exception e) {
            // TODO: handle exception
        }


    }
}